<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <!-- <el-form-item label="对话编号" prop="conversationId">
        <el-input
          v-model="queryParams.conversationId"
          placeholder="请输入对话编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="回复编号" prop="replyId">
        <el-input
          v-model="queryParams.replyId"
          placeholder="请输入回复编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="姓名" prop="candidateName">
        <el-input
          v-model="queryParams.candidateName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="电话" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入电话"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="公司名字" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择公司"
          clearable
          filterable
          class="!w-240px"
        >
          <el-option
            v-for="item in companyOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="消息类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择消息类型"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>

      <el-form-item label="模型编号" prop="modelId">
        <el-input
          v-model="queryParams.modelId"
          placeholder="请输入模型编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="是否携带上下文" prop="useContext">
        <el-select
          v-model="queryParams.useContext"
          placeholder="请选择是否携带上下文"
          clearable
          class="!w-240px"
        >
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item>
      <el-form-item label="段落编号数组" prop="segmentIds">
        <el-input
          v-model="queryParams.segmentIds"
          placeholder="请输入段落编号数组"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-220px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <!-- <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['system:chat-message1:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['system:chat-message1:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="姓名" align="center" prop="candidateName" />
      <el-table-column label="电话" align="center" prop="mobile" />
      <el-table-column label="公司名字" align="center" prop="companyName" />
      <el-table-column label="招聘职位" align="center" prop="companyRequirementName" />
      <el-table-column label="评分" align="center" prop="score" />
      <el-table-column label="分析结果" align="center" prop="content" min-width="160px" />
      <!-- <el-table-column label="是否推荐面试" align="center" prop="recommendInterview" /> -->
      <!--改成 Switch 1 录用 0 未录用 -->
      <el-table-column label="是否录用" align="center" prop="employed" min-width="160px">
        <template #default="scope">
          <el-switch
            :model-value="scope.row.employed === '1'"
            @change="(value) => handleEmployedChange(scope.row, value ? '1' : '0')"
            active-text="已录用"
            inactive-text="未录用"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="是否录用" align="center" prop="employed">
        <template #default="scope">
          <el-tag v-if="scope.row.employed == 1" type="success">已录用</el-tag>
          <el-tag v-else type="danger">未录用</el-tag>
        </template>
      </el-table-column> -->

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <!-- <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['system:chat-message1:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['system:chat-message1:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <ChatMessage1Form ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ChatMessage1Api, ChatMessage1VO } from '@/api/system/chatmessage1'
import ChatMessage1Form from './ChatMessage1Form.vue'
import { CompanyApi, CompanyVO } from '@/api/system/company'

/** AI 聊天消息 列表 */
defineOptions({ name: 'ChatMessage1' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<ChatMessage1VO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  conversationId: undefined,
  replyId: undefined,
  candidateName: undefined,
  mobile: undefined,
  type: undefined,
  companyId: undefined,
  modelId: undefined,
  content: undefined,
  useContext: undefined,
  segmentIds: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const companyOptions = ref<CompanyVO[]>([]) // 公司选项列表

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await ChatMessage1Api.getChatMessage1Page(queryParams)
    // 确保employed属性有正确的类型
    list.value = data.list.map((item: any) => ({
      ...item,
      employed: item.employed === 1 || item.employed === '1' ? '1' : '0'
    }))
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 获取公司列表 */
const getCompanyList = async () => {
  try {
    // 查询所有公司
    const res = await CompanyApi.getCompanyPage({
      pageNo: 1,
      pageSize: 100 // 设置一个较大的值，确保获取所有公司
    })
    companyOptions.value = res.list
  } catch (error) {
    console.error('获取公司列表失败:', error)
    message.error('获取公司列表失败')
  }
}

/** 是否录用操作 */
const handleEmployedChange = async (row: any, value: string) => {
  try {
    loading.value = true
    // 如果值没变，不做任何操作
    if (value === row.employed) return

    // 复制行数据，避免直接修改引用
    const updatedRow: any = {
      ...row,
      segmentIds: null,
      employed: value === '1' ? 1 : 0
    }

    // 调用API更新状态
    await ChatMessage1Api.updateChatMessage1(updatedRow)

    // 提示更新成功
    message.success(t('common.updateSuccess'))

    // 更新本地列表中的数据
    const index = list.value.findIndex((item) => item.id === row.id)
    if (index !== -1) {
      list.value[index].employed = value
    }

    // 重新获取列表
    await getList()
  } catch (error) {
    console.error('更新状态失败:', error)
    message.error('更新状态失败，请重试')
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
// const openForm = (type: string, id?: number) => {
//   formRef.value.open(type, id)
// }

/** 删除按钮操作 */
// const handleDelete = async (id: number) => {
//   try {
//     // 删除的二次确认
//     await message.delConfirm()
//     // 发起删除
//     await ChatMessage1Api.deleteChatMessage1(id)
//     message.success(t('common.delSuccess'))
//     // 刷新列表
//     await getList()
//   } catch {}
// }

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ChatMessage1Api.exportexcel(queryParams)
    download.excel(data, 'AI简历分析历史.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
  getCompanyList() // 获取公司列表
})
</script>
